import React from 'react'
import { Upload, Button, message } from 'antd'
import request from '@/utils/request'
import IconSvg from '@/components/IconSvg'
import styles from './index.module.less'
import { IPressure } from '@/@types/common'
import { isNullData } from '@/utils'

interface IProps {
  id: string
  importSuccess: () => void
}

export default (props: IProps) => {
  const { importSuccess, id } = props
  const handleFileUpload = async (file) => {
    const formData = new FormData()
    formData.append('file', file)
    formData.append('id', id)
    try {
      const response = await request.post('/dataReport/importInjuryInformation', formData, {
        headers: {
          'Content-Type': 'multipart/form-data',
        },
      })
      if (isNullData(response) && Number(response.data.success) === 1) {
        message.error(response.data.message || '文件导入失败')
        importSuccess()
        return
      }
      if (isNullData(response)) {
        importSuccess()
        message.success('文件导入成功！')
      }
      // 处理上传成功的逻辑
    } catch (error) {
      // 处理上传失败的逻辑
      console.error(error)
      message.error('导入失败，请重试！')
    }
  }

  const handleUpload = (info) => {
    if (info.file.status === 'done') {
      handleFileUpload(info.file.originFileObj)
    } else if (info.file.status === 'error') {
      message.error('文件导入失败！')
    }
  }

  return (
    <Upload
      className={styles.UploadWrapper}
      accept='.xlsx, .xls'
      customRequest={({ file }) => handleFileUpload(file)}
      onChange={handleUpload}
      showUploadList={false} // 隐藏上传列表
    >
      <Button style={{ marginRight: '16px' }} icon={<IconSvg name='lead-into' style={{ marginRight: '8px' }} />}>
        导入事件数据
      </Button>
    </Upload>
  )
}
